import {
  ryAxios
} from '../utils/request'
import { message } from 'ant-design-vue'
import Qs from 'qs'

function $get () {
  let args = Array.prototype.slice.call(arguments)
  args[1] = args[1] || {}
  args[2] = args[2] || {}
  return $http.apply(null, (args = args.concat('get')))
}

function $post () {
  let args = Array.prototype.slice.call(arguments)
  args[1] = args[1] || {}
  args[2] = args[2] || {}
  return $http.apply(null, (args = args.concat('post')))
}

function $put () {
  let args = Array.prototype.slice.call(arguments)
  args[1] = args[1] || {}
  args[2] = args[2] || {}
  return $http.apply(null, (args = args.concat('put')))
}

function $delete () {
  let args = Array.prototype.slice.call(arguments)
  args[1] = args[1] || {}
  args[2] = args[2] || {}
  return $http.apply(null, (args = args.concat('delete')))
}

function $list (url, data, pager, headers) {
  data = data || {}
  pager = pager || {}
  headers = headers || {}

  const param = {
    data: data,
    pager: Object.assign({}, {
      pageNum: 1,
      pageSize: 10
    }, pager)
  }
  return $http(url, param, headers, 'post')
}

function $http (url = '', parameter = {}, headers = {}, method = 'get') {
  // let _url = url, _parameter = parameter, _headers = headers, _method = method
  // const args = Array.prototype.slice.apply(arguments)
  if (!url) {
    message.error('请设置url参数!')
    return
  }
  const opts = {
    url
  }
  // eslint-disable-next-line no-undef
  if (window._UTILS.isString(headers)) {
    method = headers
    headers = {}
  }

  opts[['post', 'put'].includes(method) ? 'data' : 'params'] = parameter
  opts.method = method
  opts.headers = headers

  return window.$axios(opts)
}

// post contentType
function postActionType (url, parameter) {
  let type = 'application/x-www-form-urlencoded'
  return window.$axios({
    headers: {
      'Content-Type': type
    },
    url: url,
    method: 'post',
    data: Qs.stringify(parameter)
  })
}

const apiManage = {
  install (Vue, store, process) {
    Vue.use(ryAxios, store, process)
    window.$http = Vue.prototype.$http = $http
    window.$get = Vue.prototype.$get = $get
    window.$post = Vue.prototype.$post = $post
    window.$put = Vue.prototype.$put = $put
    window.$delete = Vue.prototype.$delete = $delete
    window.$list = Vue.prototype.$list = $list
    window.$postType = Vue.prototype.$postType = postActionType

  }
}
export default apiManage